package com.insigma.business.qrcode.common.template;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Maps;

import java.util.Map;
import java.util.concurrent.TimeUnit;


public class MemCacheManager {
    private static Map<String, Cache<String, Object>> cacheMap = Maps.newHashMap();

    public static Cache<String, Object> getInstance() {
        return getInstance(1L, TimeUnit.HOURS);
    }

    public static Cache<String, Object> getInstance(long duration, TimeUnit unit) {
        long d = unit.toSeconds(duration);
        String key = String.valueOf(d);

        Cache cache = cacheMap.get(key);
        if (cache == null) {
            synchronized (MemCacheManager.class) {
                cache = cacheMap.get(key);
                if (cache == null) {
                    Cache<String, Object> build = CacheBuilder.newBuilder().expireAfterWrite(duration, unit).build();
                    cacheMap.put(key, build);
                    cache = build;
                }
            }
        }
        return cache;
    }
}
